<!--
 * createor: zc
 * email: zc8023zs@163.com
 * create_time: 2020/3/14 13:46:24
 *-->
<template>
  <div class="app-container">  
    <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" v-show="permissions.p_add" type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
        </el-button> 
    </div>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      border
      row-key="id">
      <el-table-column
        show-overflow-tooltip
        prop="class_name"
        label="参数名称"
        width="180">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="name"
        label="标识名"
        align="center"
        width="300">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="number_value"
        label="数值"
        align="center"
        width="100">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="date_value"
        label="日期"
        align="center"
        width="110"
        :formatter="dateFormat">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="time_value"
        label="时间"
        align="center"
        width="160">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="string_value"
        align="center"
        label="字符">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="remark"
        align="center"
        label="备注"
        width="300">
      </el-table-column>
      <el-table-column v-if="permissions.operation" :label="$t('table.actions')" align="center" width="130" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" v-show="permissions.p_edit" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button> 
          <!-- <el-button  size="mini" v-show="permissions.p_del" type="danger" @click="handleDelete(row)">
            {{ $t('table.delete') }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal='false' :visible.sync="dislogParamsTree" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" >
        <el-form-item label="参数名称" prop="class_name">
          <input type="hidden" v-model="temp.id" />
          <el-input maxlength="101" v-model.trim="temp.class_name" />
        </el-form-item>  
        <el-form-item label="上级参数">   
          <treeselect
              :options="deptPParamsData"
              :default-expand-level="1"
              placeholder="请选择上级参数"
              v-model="tree"
              :normalizer="normalizer"
            />
        </el-form-item> 
        <el-form-item label="标识名" prop="name">
          <el-input maxlength="101" v-model.trim="temp.name"/>
        </el-form-item>   
        <el-form-item label="数值参数">
          <el-input-number v-model="temp.number_value" :max="99999999" :min="-99999999"/>
        </el-form-item> 
        <el-form-item label="日期参数">
            <el-date-picker
                v-model="temp.date_value"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>   
        <el-form-item label="时间参数"> 
            <el-date-picker 
                v-model="temp.time_value"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>   
        <el-form-item label="字符串参数">
          <el-input maxlength="9999" v-model.trim="temp.string_value"/>
        </el-form-item>   
        <el-form-item label="备注">
          <el-input maxlength="300" v-model="temp.remark"/>
        </el-form-item>  
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dislogParamsTree = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>  
  </div>
</template>

<script>
import { fetchList, fetchObj, createObj, updateObj, getPParams, deleteObj } from '@/api/project/system/project_sys_sys_params'
import { Loading } from 'element-ui';
// import the component
import treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: 'a_systema_sys_params',
  components: { treeselect },
  filters: {
  },
  data() {
      return {
        tableKey: 0,
        temp: {
          id: 0,
          pid: 0,
          pname:'顶级',
          class_name:'',
          name: '',
          number_value: '',
          date_value: '',
          time_value: '',
          string_value: '',
          remark: ''
        }, 
        permissions:{
          p_select:false,
          p_add:false,
          p_edit: false,
          p_del: false,
          operation: false,
        },
        tree:null,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '添加'
        }, 
        rules: {
          class_name: [{ required: true, message: '参数名称必填', trigger: 'change' },
          { type: "string", max: 100, message: "参数名称不超过100个字", trigger: "blur"} 
          ],
          name: [{ required: true, message: '标识必填', trigger: 'change' },
          { type: "string", max: 100, message: "标识不超过100个字", trigger: "blur"} ]
        },  
        tableData:  null,
        dislogParamsTree: false,
        deptPParamsData: null,
      }
  },
  created() { 
    this.getList();
    this.$per(result=>{ 
      this.permissions.p_select=result['*/system/sysparams/getSysParamsList']!=null;
      this.permissions.p_add=result['*/system/sysparams/addSysParams']!=null;
      this.permissions.p_edit=result['*/system/sysparams/updateSysParams']!=null;
      this.permissions.p_del=result['*/system/sysparams/deleteSysParam']!=null;
      if(result['*/system/sysparams/updateSysParams']!=null || result['*/system/sysparams/deleteSysParam']!=null){
            this.permissions.operation=true;
      }
    })
  },
  methods: {  
    openFullScreen() {
        const loading = this.$loading({
          lock: true,
          text: '数据处理中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        }); 
        setTimeout(() => {
          loading.close();
        }, 2000);
    },
     normalizer(node) {
      if (node.children == undefined || node.children == null || node.children.length==0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.class_name,
        children: node.children
      };
    },
    dateFormat(row, column) {
        // 获取单元格数据
        let data = row[column.property]
        if (!data) {
            return ''
        }
        let dt = new Date(data)
        return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    getList() { 
      fetchList().then(response => {
        this.tableData = response.dataArray.dataList;
        this.deptPParamsData = response.dataArray.dataList;
      })
    }, 
    resetTemp() {
      this.temp = {
          id: 0,
          pid: null,
          pname:'',
          class_name:'',
          name: '',
          number_value: '',
          date_value: '',
          time_value: '',
          string_value: '',
          remark: ''
      },
      this.tree=null;
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dislogParamsTree = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {  
          this.openFullScreen();
          if(this.tree==""|| this.tree==null || this.tree==undefined){
            this.temp.pid=0;
          }else{
            this.temp.pid=this.tree;
          }
          createObj(this.temp).then(res => {
            this.dislogParamsTree = false;
            this.getList();
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dislogParamsTree = true
      if(this.temp.pid==0){
        this.tree=null;
      }else{
        this.tree=this.temp.pid
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) { 
          this.openFullScreen();
          if(this.tree==""|| this.tree==null || this.tree==undefined){
            this.temp.pid=0;
          }else{
            this.temp.pid=this.tree;
          }
          const tempData = Object.assign({}, this.temp); 
          tempData.children='';
          updateObj(tempData).then(res => { 
            this.dislogParamsTree = false;
            this.getList();
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleDelete(row) { 
      this.$confirm('确定删除该参数？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.openFullScreen();
        deleteObj(row).then(res => { 
          this.getList();
          if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
  }
}
</script>